const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const Cleanannotation = require('webpack-clean-annotation-plugin')
const file = require.context('./src', false, '/\.js$/')
console.log(file, 'file')
// const MiniCss
class MyPlugin {
  constructor (options) {
    this.options = options
  }

  apply (compiler) {
    console.log('pkugin start')
    compiler.hooks.emit.tap('MyPlugin', compilation => { // emit 为执行时机 挂载的钩子函数
      console.log(this, '==========')
      Object.keys(compilation.assets).map(item => {
        if (item.endsWith('.js')) {
          const withOutComments = compilation.assets[item].source().replace(/\/\*\*+\*\//g, '')
          compilation.assets[item] = {
            source: () => withOutComments,
            size: () => withOutComments.length
          }
        }
      })
    })
  }
}
module.exports = {
  mode: 'none',
  entry: './src/main.js',
  output: {
    filename: 'main.js',
    path: path.join(__dirname, 'dist'),
    publicPath: 'dist'
  },
  devServer: {
    port: 8080
  },
  // devtool:'cheap-module-eval-source-map',
  module: {
    rules: [
      {
        test: /\.css/,
        use: ['style-loader', 'css-loader']
      },
      {
        test: /.md/,
        use: ['mdzlh-loader']
      }
    ]
  },
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: './src/index.html'
    }),
    new Cleanannotation({ a: 1 })
  ],
  optimization: {
    splitChunks: {
      chunks: 'all' // 默认作用于异步chunk，值为all/initial/async/function(chunk),值为function时第一个参数为遍历所有入口chunk时的chunk模块，chunk._modules为chunk所有依赖的模块，通过chunk的名字和所有依赖模块的resource可以自由配置,会抽取所有满足条件chunk的公有模块，以及模块的所有依赖模块，包括css
      // minSize: 30000,  //表示在压缩前的最小模块大小,默认值是30kb
      // minChunks: 1,  // 表示被引用次数，默认为1；
      // maxAsyncRequests: 5,  //所有异步请求不得超过5个
      // maxInitialRequests: 3,  //初始话并行请求不得超过3个
      // automaticNameDelimiter:'~',//名称分隔符，默认是~
      // name: true,  //打包后的名称，默认是chunk的名字通过分隔符（默认是～）分隔
      // cacheGroups: { //设置缓存组用来抽取满足不同规则的chunk,下面以生成common为例
      //   vendors: {
      //     test: /[\\/]node_modules[\\/]/, //表示只筛选从node_modules文件夹下引入的模块
      //     priority: -10,
      //     chunks: 'all'
      //   },
      //   commons: {
      //       name: 'commons',
      //       chunks: 'initial',
      //       minChunks: 2,
      //       reuseExistingChunk: true,
      //   },
      //   default: {
      //       minChunks: 1,
      //       priority: -20,
      //       reuseExistingChunk: true,
      //   }
      // }
    }
  }
}
